package com.closer.service.biz.cos.service.impl;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.closer.service.biz.cos.manage.CosManager;
import com.closer.service.biz.cos.service.ScreenshotService;
import com.closer.service.support.exception.ErrorCode;
import com.closer.service.support.exception.ThrowUtils;
import com.closer.service.support.utils.WebScreenshotUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Service
@Slf4j
public class ScreenshotServiceImpl implements ScreenshotService {

    private final CosManager cosManager;

    public ScreenshotServiceImpl(CosManager cosManager) {
        this.cosManager = cosManager;
    }

    @Override
    public String generateAndUploadScreenshot(String webUrl){
        ThrowUtils.throwIf(StrUtil.isBlank(webUrl), ErrorCode.PARAMS_ERROR, "网页地址不能为空");
        log.info("开始生成网页截图,URL:{}", webUrl);
        //1.生成本地截图
        var localScreenshotPath = WebScreenshotUtils.saveWebPageScreenshot(webUrl);
        try {
            //2.上传到对象存储
            var cosUrl = uploadScreenshotToCos(localScreenshotPath);
            ThrowUtils.throwIf(StrUtil.isBlank(cosUrl),ErrorCode.OPERATION_ERROR,"截图上传对象存储失败");
            log.info("网页截图生成并上传成功：{} ->{}",webUrl, cosUrl);
            return cosUrl;
        } finally {
            //3.清理本地文件
            cleanupLocalFile(localScreenshotPath);
        }

    }

    /**
     *  上传截图到对象存储
     *
     *  @param localScreenshotPath 本地截图路径
     * @return 对象存储URL
     */
    private String uploadScreenshotToCos(String localScreenshotPath) {
        if(StrUtil.isBlank(localScreenshotPath)){
            return null;
        }
        var screenshotFile = new File(localScreenshotPath);
        if(!screenshotFile.exists()){
            log.error("截图文件不存在：{}",localScreenshotPath);
            return null;
        }
        // 生成COS对象键
        var fileName = UUID.randomUUID().toString().substring(0,8) + "_compressed.jpg";
        var cosKey = generateScreenshotKey(fileName);
        return cosManager.uploadFile(cosKey, screenshotFile);
    }

    /**
     * 生成截图对象键
     * 格式：/screenshots/2025/07/31/filename.jpg
     */
    private String generateScreenshotKey(String fileName) {
        var datePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        return String.format("/screenshots/%s/%s",datePath,fileName);
    }

    /**
     * 清理本地文件
     *
     * @param localFilePath 本地文件路径
     */
    private void cleanupLocalFile(String localFilePath){
        var localFile = new  File(localFilePath);
        if (localFile.exists()){
            var parentDir = localFile.getParentFile();
            FileUtil.del(parentDir);
            log.info("删除本地文件成功：{}",localFilePath);
        }
    }

}
